package org.smart4j.framework.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * 切面代理
 * @Description:
 * @Author: Administrator
 * @Date: 2017/9/4 0004 下午 8:43
 */
public abstract class AspectProxy implements Proxy {

    private static final Logger logger = LoggerFactory.getLogger(AspectProxy.class);

    @Override
    public final Object doProxy(ProxyChain proxyChain) throws Throwable {
        Object resultObj = null;

        Class<?> cls = proxyChain.getTargetClass();
        Method method = proxyChain.getTargetMethod();
        Object[] params = proxyChain.getMethodParams();
        begin();
        try {
            if (intercept(cls, method, params)) {
                before(cls, method, params);
                resultObj = proxyChain.doProxyChain();
                after(cls,method,params);
            }
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("proxy failure", e);
                error(cls, method, params);
                throw e;
            }
        } finally {
            end();
        }

        return resultObj;
    }

    public void error(Class<?> cls, Method method, Object[] params) throws Throwable{
    }

    private void end() {
    }

    public void after(Class<?> cls, Method method, Object[] params) throws Throwable {
    }

    public void before(Class<?> cls, Method method, Object[] params) throws Throwable {
    }

    public boolean intercept(Class<?> cls, Method method, Object[] params)throws Throwable {
        return true;
    }

    public void begin() {

    }
}
